package dk.aiszone.lang.messer.autosource;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import dk.aiszone.lang.autosource.generatorobjects.Class;
import dk.aiszone.lang.autosource.generatorobjects.interfaces.GeneratorObject;
import dk.aiszone.lang.autosource.generatorobjects.interfaces.SimpleBlockObject;

/**
 * The <code>LocalVariable</code> represents a variable declared within a body.
 * 
 * @author Ais
 */
public class LocalVariable extends GeneratorObject implements SimpleBlockObject {

    private final List<VariableAssignment> assignments = new ArrayList<VariableAssignment>();
    private final Class type;

    /**
     * Constructor for the <code>LocalVariable</code>.
     * 
     * @param type
     *            The type of variable being declared.
     */
    public LocalVariable(Class type) {
        this.type = type;
    }

    /**
     * Add a <code>VariableAssignment</code> to the <code>LocalVariable</code> declaration.
     * 
     * @param assignment
     *            The <code>VariableAssignment</code> to add.
     */
    public void addVariable(VariableAssignment assignment) {
        assignments.add(assignment);
    }

    @Override
    public Object clone() {
        List<VariableAssignment> cloneAssignments = new ArrayList<VariableAssignment>();
        for (Iterator<VariableAssignment> iterator = assignments.iterator(); iterator.hasNext();) {
            cloneAssignments.add((VariableAssignment)iterator.next().clone());
        }

        LocalVariable clone = new LocalVariable((Class)type.clone());
        clone.assignments.addAll(cloneAssignments);
        return clone;
    }

    @Override
    public SimpleBlockObject getChild(int index) {
        return assignments.get(index);
    }

    @Override
    public int getChildCount() {
        return assignments.size();
    }

    @Override
    public String toJava() {
        StringBuilder sb = new StringBuilder();
        sb.append(type.getClassName()).append(" ");
        for (Iterator<VariableAssignment> iterator = assignments.iterator(); iterator.hasNext();) {
            sb.append(iterator.next().toJava());
            if (iterator.hasNext()) {
                sb.append(", ");
            }
        }

        return sb.toString();
    }
}
